package com.itheima;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.ArrayList;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

public class Preview {
    public void previewImage(String filePath)throws IOException{
        File imageFile = new File(filePath);
        BufferedImage image = ImageIO.read(imageFile);

        JFrame previewFrame = new JFrame("图片预览: " + imageFile.getName());
        previewFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        previewFrame.setSize(400, 300);
        previewFrame.setLocationRelativeTo(null);

        // 创建自定义面板用于显示图片
        ImagePanel imagePanel = new ImagePanel(image);
        JScrollPane scrollPane = new JScrollPane(imagePanel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        previewFrame.getContentPane().add(scrollPane, BorderLayout.CENTER);

        // 添加窗口大小改变的监听器，以便实时调整图片大小
        previewFrame.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                imagePanel.adjustImageSize();
            }
        });
        previewFrame.setVisible(true);
        // 初始调整图片大小
        imagePanel.adjustImageSize();

    }
    private static class ImagePanel extends JPanel {
        private BufferedImage originalImage;
        private Image scaledImage;
        private double scaleFactor = 1.0;

        public ImagePanel(BufferedImage image) {
            this.originalImage = image;
            setLayout(new BorderLayout());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (scaledImage != null) {
                // 居中绘制图片
                int x = (getWidth() - scaledImage.getWidth(null)) / 2;
                int y = (getHeight() - scaledImage.getHeight(null)) / 2;
                g.drawImage(scaledImage, x, y, this);
            }
        }

        // 调整图片大小以适应面板
        public void adjustImageSize() {
            if (originalImage == null) return;

            int panelWidth = getWidth();
            int panelHeight = getHeight();

            // 如果面板尚未初始化大小，使用父容器的大小
            if (panelWidth <= 0 || panelHeight <= 0) {
                Container parent = getParent();
                if (parent != null) {
                    panelWidth = parent.getWidth();
                    panelHeight = parent.getHeight();
                }
            }


            double widthRatio = (double) panelWidth / originalImage.getWidth();
            double heightRatio = (double) panelHeight / originalImage.getHeight();
            scaleFactor = Math.min(widthRatio, heightRatio);


            scaleFactor = Math.min(scaleFactor, 1.0);

            // 缩放图片
            if (scaleFactor > 0) {
                int newWidth = (int) (originalImage.getWidth() * scaleFactor);
                int newHeight = (int) (originalImage.getHeight() * scaleFactor);
                scaledImage = originalImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
                repaint();
            }
        }
    }
    public boolean isImageFile(String filePath){
        if (filePath == null) {
            System.out.println("路径为空");
            return false;
        }
        String lowerCasePath=filePath.toLowerCase();
        return lowerCasePath.endsWith(".jpg") || lowerCasePath.endsWith(".png")||
                lowerCasePath.endsWith(".gif") || lowerCasePath.endsWith(".bmp")||
                lowerCasePath.endsWith(".jpeg") || lowerCasePath.endsWith(".webp");
    }
//---------------------------------------------------------------------------------------------------------------
    private JFrame previewFrame;
    private PDDocument document;
    private PDFRenderer pdfRenderer;
    private int currentPage = 0;
    private JLabel imageLabel;
    private JSpinner pageSpinner;
    private JLabel pageInfoLabel;
    private float scale = 1.0f;
    private JPanel mainPanel;
    public void previewPDF(String filePath) {
        try {
            // 加载PDF文档
            document = PDDocument.load(new File(filePath));
            pdfRenderer = new PDFRenderer(document);

            // 创建预览窗口
            previewFrame = new JFrame("PDF预览: " + new File(filePath).getName());
            previewFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            previewFrame.setSize(400, 300);
            previewFrame.setLocationRelativeTo(null);

            // 创建主面板
            mainPanel = new JPanel(new BorderLayout());

            // 创建PDF显示区域
            imageLabel = new JLabel();
            imageLabel.setHorizontalAlignment(JLabel.CENTER);
            imageLabel.setVerticalAlignment(JLabel.CENTER);
            JScrollPane scrollPane = new JScrollPane(imageLabel);
            scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
            mainPanel.add(scrollPane, BorderLayout.CENTER);

            // 创建控制工具栏
            createControlPanel();

            // 添加窗口关闭监听器
            previewFrame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    closeDocument();
                }
            });

            previewFrame.setContentPane(mainPanel);
            previewFrame.setVisible(true);

            // 显示第一页
            showPage(0);
        } catch (IOException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(null, "无法加载PDF文件: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void createControlPanel() {
        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 5));

        // 上一页按钮
        JButton prevButton = new JButton("上一页");
        prevButton.addActionListener(e -> showPreviousPage());

        // 下一页按钮
        JButton nextButton = new JButton("下一页");
        nextButton.addActionListener(e -> showNextPage());

        // 放大按钮
        JButton zoomInButton = new JButton("放大");
        zoomInButton.addActionListener(e -> zoomIn());

        // 缩小按钮
        JButton zoomOutButton = new JButton("缩小");
        zoomOutButton.addActionListener(e -> zoomOut());

        // 页面选择器
        int pageCount = document != null ? document.getNumberOfPages() : 1;
        SpinnerModel spinnerModel = new SpinnerNumberModel(1, 1, pageCount, 1);
        pageSpinner = new JSpinner(spinnerModel);
        pageSpinner.setPreferredSize(new Dimension(60, 25));
        pageSpinner.addChangeListener(e -> {
            int page = (int) pageSpinner.getValue() - 1;
            showPage(page);
        });

        // 页面信息标签
        pageInfoLabel = new JLabel("第 1 页 / 共 " + pageCount + " 页");

        // 添加组件到控制栏
        controlPanel.add(prevButton);
        controlPanel.add(nextButton);
        controlPanel.add(new JLabel("缩放:"));
        controlPanel.add(zoomInButton);
        controlPanel.add(zoomOutButton);
        controlPanel.add(new JLabel("跳转到第:"));
        controlPanel.add(pageSpinner);
        controlPanel.add(new JLabel("页"));
        controlPanel.add(pageInfoLabel);

        mainPanel.add(controlPanel, BorderLayout.SOUTH);
    }

    private void showPage(int pageIndex) {
        if (document == null || pageIndex < 0 || pageIndex >= document.getNumberOfPages()) {
            return;
        }

        try {
            currentPage = pageIndex;
            // 渲染PDF页面为图像
            BufferedImage image = pdfRenderer.renderImageWithDPI(currentPage, 96 * scale);
            imageLabel.setIcon(new ImageIcon(image));
            imageLabel.repaint();

            // 更新页面信息
            pageSpinner.setValue(currentPage + 1);
            pageInfoLabel.setText("第 " + (currentPage + 1) + " 页 / 共 " + document.getNumberOfPages() + " 页");
        } catch (IOException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(null, "无法渲染PDF页面: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void showPreviousPage() {
        if (currentPage > 0) {
            showPage(currentPage - 1);
        }
    }

    private void showNextPage() {
        if (currentPage < document.getNumberOfPages() - 1) {
            showPage(currentPage + 1);
        }
    }

    private void zoomIn() {
        scale *= 1.2f;
        showPage(currentPage);
    }

    private void zoomOut() {
        scale /= 1.2f;
        showPage(currentPage);
    }

    private void closeDocument() {
        if (document != null) {
            try {
                document.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            document = null;
        }
    }
//---------------------------------------------------------------------------------------------------------------------

    public void previewWord(String filePath) {
        try {
            // 创建预览窗口
            JFrame previewFrame = new JFrame("Word预览: " + new File(filePath).getName());
            previewFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            previewFrame.setSize(400, 300);
            previewFrame.setLocationRelativeTo(null);

            // 创建文本区域用于显示Word内容
            JTextArea textArea = new JTextArea();
            textArea.setEditable(false);
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);

            // 添加滚动条
            JScrollPane scrollPane = new JScrollPane(textArea);

            // 读取Word文档内容
            try (FileInputStream fis = new FileInputStream(filePath);
                 XWPFDocument document = new XWPFDocument(fis)) {

                // 提取所有段落文本
                StringBuilder content = new StringBuilder();
                for (XWPFParagraph paragraph : document.getParagraphs()) {
                    content.append(paragraph.getText()).append("\n\n");
                }

                // 在文本区域显示内容
                textArea.setText(content.toString());
                textArea.setCaretPosition(0); // 滚动到顶部
            } catch (IOException ex) {
                ex.printStackTrace();
                textArea.setText("无法读取Word文档: " + ex.getMessage());
            }

            previewFrame.getContentPane().add(scrollPane, BorderLayout.CENTER);
            previewFrame.setVisible(true);
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(null, "预览Word文档时出错: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

//---------------------------------------------------------------------------------------------------------------------

    public void previewExcel(String filePath) {
        try {
            // 创建预览窗口
            JFrame previewFrame = new JFrame("Excel预览: " + new File(filePath).getName());
            previewFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            previewFrame.setSize(400, 300);
            previewFrame.setLocationRelativeTo(null);

            // 创建表格模型和表格
            DefaultTableModel tableModel = new DefaultTableModel();
            JTable table = new JTable(tableModel);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

            // 添加滚动条
            JScrollPane scrollPane = new JScrollPane(table);

            // 读取Excel文档内容
            try (FileInputStream fis = new FileInputStream(filePath);
                 Workbook workbook = new XSSFWorkbook(fis)) {

                // 获取第一个工作表
                Sheet sheet = workbook.getSheetAt(0);
                if (sheet == null) {
                    tableModel.setRowCount(0);
                    tableModel.setColumnCount(0);
                    throw new IOException("Excel文件中没有工作表");
                }

                // 获取最大列数
                int maxColumns = 0;
                for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (row != null && row.getLastCellNum() > maxColumns) {
                        maxColumns = (int) row.getLastCellNum();
                    }
                }

                // 设置表格列标题（假设第一行为标题）
                String[] columnNames = new String[maxColumns];
                Row headerRow = sheet.getRow(0);
                if (headerRow != null) {
                    for (int i = 0; i < maxColumns; i++) {
                        Cell cell = headerRow.getCell(i);
                        columnNames[i] = cell != null ? getCellValueAsString(cell) : "列 " + (i + 1);
                    }
                } else {
                    for (int i = 0; i < maxColumns; i++) {
                        columnNames[i] = "列 " + (i + 1);
                    }
                }
                tableModel.setColumnIdentifiers(columnNames);

                // 填充表格数据（从第二行开始）
                List<Object[]> data = new ArrayList<>();
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (row != null) {
                        Object[] rowData = new Object[maxColumns];
                        for (int j = 0; j < maxColumns; j++) {
                            Cell cell = row.getCell(j);
                            rowData[j] = cell != null ? getCellValueAsString(cell) : "";
                        }
                        data.add(rowData);
                    }
                }

                // 添加数据到表格模型
                for (Object[] rowData : data) {
                    tableModel.addRow(rowData);
                }

                // 自动调整列宽
                for (int i = 0; i < maxColumns; i++) {
                    table.getColumnModel().getColumn(i).setPreferredWidth(120);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, "无法读取Excel文档: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }

            previewFrame.getContentPane().add(scrollPane, BorderLayout.CENTER);
            previewFrame.setVisible(true);
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(null, "预览Excel文档时出错: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private String getCellValueAsString(Cell cell) {
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            case BLANK:
                return "";
            default:
                return cell.toString();
        }
    }


}